import 'package:flutter/material.dart';
import 'package:flutter/services.dart';


class Scene09SuggestionReplace extends StatefulWidget {
  const Scene09SuggestionReplace({super.key});
  @override
  State<Scene09SuggestionReplace> createState() => _Scene09SuggestionReplaceState();
}

class _Scene09SuggestionReplaceState extends State<Scene09SuggestionReplace>
    implements DeltaTextInputClient {
  late final TextInputConnection _conn;
  TextEditingValue _value = const TextEditingValue(text: 'Helo'); // 故意拼错
  final List<String> _logs = [];

  /* === DeltaTextInputClient === */
  @override
  TextEditingValue get currentTextEditingValue => _value;

  @override
  void updateEditingValueWithDeltas(List<TextEditingDelta> deltas) {
    for (final d in deltas) {
      if (d is TextEditingDeltaReplacement) {
        _logs.add(
          '建议条替换: "${d.textReplaced}" → "${d.replacementText}" '
              '@${d.replacedRange.start}-${d.replacedRange.end}',
        );
      }
    }
    setState(() {
      for (final d in deltas) _value = d.apply(_value);
    });
  }

  /* 其余空实现，零报错 */
  @override
  void updateEditingValue(TextEditingValue value) {}
  @override
  void performAction(TextInputAction action) {}
  @override
  void connectionClosed() {}

  @override
  void insertContent(KeyboardInsertedContent content) {}
  @override
  void insertTextPlaceholder(Size size) {}
  @override
  void performPrivateCommand(String action, Map<String, dynamic> data) {}
  @override
  void performSelector(String selectorName) {}
  @override
  void removeTextPlaceholder() {}
  @override
  void showAutocorrectionPromptRect(int start, int end) {}
  @override
  void showToolbar() {}
  @override
  void updateFloatingCursor(RawFloatingCursorPoint point) {}

  /* === 生命周期 === */
  @override
  void initState() {
    super.initState();
    _conn = TextInput.attach(
      this,
      const TextInputConfiguration(enableDeltaModel: true),
    )
      ..show()
      ..setEditingState(_value);
  }

  @override
  void dispose() {
    _conn.close();
    super.dispose();
  }

  /* === 手动触发建议条替换 === */
  void _suggestReplace() {
    final replaced = _value.text;
    final replacement = 'Hello'; // 键盘建议的正确单词
    final delta = TextEditingDeltaReplacement(
      oldText: _value.text,
      replacedRange: TextRange(start: 0, end: replaced.length),
      replacementText: replacement,
      composing: TextRange(start: 0, end: replaced.length),
      selection: TextSelection(baseOffset: 0, extentOffset: replaced.length)
    );
    updateEditingValueWithDeltas([delta]);
  }

  /* === UI === */
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('键盘建议条替换 Delta')),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              padding: const EdgeInsets.all(8),
              itemCount: _logs.length,
              itemBuilder: (_, i) => Text(_logs[i],
                  style: const TextStyle(fontSize: 12, fontFamily: 'monospace')),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(12),
            child: TextField(
              controller: TextEditingController.fromValue(_value),
              decoration: const InputDecoration(
                hintText: '原始：Helo（拼错）',
                border: OutlineInputBorder(),
              ),
              onChanged: (_) {},
            ),
          ),
          ElevatedButton(
            onPressed: _suggestReplace,
            child: const Text('触发键盘建议条替换'),
          ),
        ],
      ),
    );
  }

  @override
  // TODO: implement currentAutofillScope
  AutofillScope? get currentAutofillScope => throw UnimplementedError();

  @override
  void didChangeInputControl(TextInputControl? oldControl, TextInputControl? newControl) {
    // TODO: implement didChangeInputControl
  }
}